package com.gcph.zhuoba.main.activitys;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.gcph.zhuoba.R;
import com.gcph.zhuoba.main.bean.Ball;
import com.gcph.zhuoba.main.bean.Desk;
import com.gcph.zhuoba.main.bean.Element;
import com.gcph.zhuoba.main.bean.SocketData;
import com.gcph.zhuoba.main.common.BaseActivity;
import com.gcph.zhuoba.main.common.Constant;
import com.gcph.zhuoba.main.view.BilliardsDeskView;
import com.gcph.zhuoba.util.ImageUtil;
import com.gcph.zhuoba.util.L;
import com.gcph.zhuoba.util.SocketClient;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class TeachingMainActivity extends BaseActivity {
	//退出
    private Button btn_teaching_quit;
    //采集球型
    private Button btn_teaching_collection;
    private Button btn_teaching_video;
    private Button btn_teaching_tools;
    private Button btn_teaching_reselect;
    private RadioGroup radio_teaching_select_ype;
    
    //教案类型 走位 K球。。。
    private Integer flag_teaching_select_ype;
    
    private LinearLayout teach_desk;
    private BilliardsDeskView billiards_desk_view;
    
    private Handler socketHandler;
    private static SocketClient socketClient;
    private String ballsPositionData;
    
    @SuppressLint("SimpleDateFormat")
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
   
    private Toast toast;
    private Context currentActivity;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//去除title
		requestWindowFeature(Window.FEATURE_NO_TITLE);  
		//去掉Activity上面的状态栏
		getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN , WindowManager.LayoutParams. FLAG_FULLSCREEN);
		//屏蔽home键
		this.getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);
		setContentView(R.layout.activity_teaching_main);
		
		teach_desk=(LinearLayout) this.findViewById(R.id.teach_desk);
		int sH = this.getScreenHeight();
		
		//桌子的高度占屏幕的60/71
		int deskH = sH*60/71;
		int deskW = deskH*Constant.imgDeskW/Constant.imgDeskH;
		
		L.d("deskH=="+deskH);
		L.d("deskW=="+deskW);
		
		billiards_desk_view = new BilliardsDeskView(this);
		
	    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(deskW,deskH);
		billiards_desk_view.setLayoutParams(params);
		teach_desk.setLayoutParams(params);
		teach_desk.addView(billiards_desk_view);
		
		btnInit();
		setBtnClickListener();
		
		currentActivity  =TeachingMainActivity.this;
		if(null == socketHandler)
		{
			socketHandler = new Handler() {
	            @Override
	            public void handleMessage(Message msg) {
	            	//配对失败
	            	if(SocketClient.PAIR_FAIL == msg.what)
	            	{
	            		showToast("请与终端配对");
	            	}
	            	
	            	if(SocketClient.PAIR_SUCC == msg.what)
	            	{
	            		showToast("请让球静止后选择采集球型");
	            	}
	            		
	            	//采集成功
	            	if(SocketClient.COLLECT_SUCC == msg.what)
	            	{
	            		//初始化可进球
	            		for(int i=0;i<Desk.canInBallList.size();i++){
	            			Desk.canInBallList.get(i).setBitmap(getBallBitmapByNo(Desk.canInBallList.get(i).getNo()));
	            		}
	            		
	            		//初始化不可进球
	            		for(int i=0;i<Desk.notCanInballList.size();i++){
	            			Desk.notCanInballList.get(i).setBitmap(getBallBitmapByNo(Desk.notCanInballList.get(i).getNo()));
	            		}
	            		for(int i=0;i<Desk.canInBallList.size();i++){
	            			L.d("可进球号："+Desk.canInBallList.get(i).getNo());
	            			L.d("可进球xy："+Desk.canInBallList.get(i).getX()+"##"+Desk.canInBallList.get(i).getY());
	            			L.d("可进球bitmap："+Desk.canInBallList.get(i).getBitmap());
	            		}
	            		for(int i=0;i<Desk.notCanInballList.size();i++){
	            			L.d("不可进球号："+Desk.notCanInballList.get(i).getNo());
	            			L.d("不可进球xy："+Desk.notCanInballList.get(i).getX()+"##"+Desk.notCanInballList.get(i).getY());
	            			L.d("不可进球bitmap："+Desk.notCanInballList.get(i).getBitmap());
	            		}
	            		
	            		//采集成功，修改状态为
	            		Desk.STEP_FLAG=Desk.STEP_FLAG_COLLECTED;
	            		//billiards_desk_view.myDraw();
	            		showToast("采集成功，请选择教案类型");
	            		//初始化球型json数据
	            		ballsPositionData = (String)msg.obj;
	            		btn_teaching_collection.setEnabled(false);
	            		selectTeachTypeDialog(currentActivity);
	            	}
	            	
	            	//选中目标球
	            	if(SocketClient.SELECTED_BALL == msg.what)
	            	{
	            		btn_teaching_tools.setEnabled(false);
	            		//K球教案
						if(Constant.RESOURCE_SMALL_TYPE_KQIU.equals(flag_teaching_select_ype))
		            	{
							showToast("请选择进球袋");
		            	}
						//防守教案
						if(Constant.RESOURCE_SMALL_TYPE_FANGSHOU.equals(flag_teaching_select_ype))
		            	{
							showToast("球型制作完成可开始录像");
							btn_teaching_video.setEnabled(true);
		            	}
						//解球教案
						if(Constant.RESOURCE_SMALL_TYPE_JIEQIU.equals(flag_teaching_select_ype))
		            	{
							showToast("球型制作完成可开始录像");
							btn_teaching_video.setEnabled(true);
		            	}
						
						//走位教案
						if(Constant.RESOURCE_SMALL_TYPE_ZOUWEI.equals(flag_teaching_select_ype))
		            	{
							showToast("请选择进球袋");
		            	}
	            	}
	            	
	            	//选中进球袋
	            	if(SocketClient.SELECTED_BAG == msg.what)
	            	{
	            		//K球教案
						if(Constant.RESOURCE_SMALL_TYPE_KQIU.equals(flag_teaching_select_ype))
		            	{
							showToast("请选择要K的球");
		            	}
						
						//走位教案
						if(Constant.RESOURCE_SMALL_TYPE_ZOUWEI.equals(flag_teaching_select_ype))
		            	{
							showToast("球型制作完成可开始录像");
							btn_teaching_video.setEnabled(true);
		            	}
	            	}
	            	
	            	//选中要K的球
	            	if(SocketClient.SELECTED_KBALL == msg.what)
	            	{
	            		showToast("球型制作完成可开始录像");
						btn_teaching_video.setEnabled(true);
	            	}
	            }
			};
		}
		
		if(null == socketClient)
		{
			socketClient = SocketClient.getInstance();
		}
		
		//----------------------配对开始----------------------------
		new Thread(new Runnable() {
			@Override
			public void run() {
				L.d("======请求配对=====");
				String socket_ip = getResources().getString(R.string.socket_ip);
				int socket_port = Integer.parseInt(getResources().getString(R.string.socket_port));
				socketClient.setUpConnection(socket_ip,socket_port,socketHandler);
				socketClient.send("{\"method\":\"102\",\"deviceid\":\"1\",\"username\":\"test\"}");
				socketClient.handleReceive();
			}
		}).start();
		//----------------------配对结束----------------------------
	}
	
	private void btnInit()
	{
		btn_teaching_collection = (Button) this.findViewById(R.id.btn_teaching_collection);
		btn_teaching_reselect = (Button) this.findViewById(R.id.btn_teaching_reselect);
		btn_teaching_tools = (Button) this.findViewById(R.id.btn_teaching_tools);
		btn_teaching_video = (Button) this.findViewById(R.id.btn_teaching_video);
		btn_teaching_quit = (Button) this.findViewById(R.id.btn_teaching_quit);
		
		btn_teaching_tools.setEnabled(false);
		btn_teaching_video.setEnabled(false);
		btn_teaching_reselect.setEnabled(false);
	}
	
	private void setBtnClickListener()
	{
		btn_teaching_quit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
            	Desk.clear();
            	//退出断开连接
            	socketClient.exit();
            	
            	ballsPositionData = null;
                finish();
            }
        });
		//采集球型
		btn_teaching_collection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
            	btn_teaching_collection.setEnabled(false);
            	Desk.clear();
            	
            	//debug模式调用测试球数据
            	if(Constant.IS_DEBUG)
            	{
            		loadBalls();
            		Desk.STEP_FLAG=Desk.STEP_FLAG_COLLECTED;
            		selectTeachTypeDialog(TeachingMainActivity.this);
            	}
            	else
            	{
                	L.d("====点击采集球型======");
            		new Runnable() {
    					@Override
    					public void run() {
    						socketClient.send("{\"method\":\"302\"}");
    					}
    				}.run();
            	}

            }
        });
		
		//重新选择
		btn_teaching_reselect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            	Desk.elementList.clear();
            	Desk.selectedBall = null;
            	Desk.selectedKBall = null;
            	Desk.selectedBag = -1;
            	Desk.STEP_FLAG=Desk.STEP_FLAG_COLLECTED;
            	billiards_desk_view.myDraw();
            	
            	btn_teaching_collection.setEnabled(false);
        		btn_teaching_video.setEnabled(false);
            	selectTeachTypeDialog(TeachingMainActivity.this);            	
            }
		});
		
		//设置元素
		btn_teaching_tools.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            	//弹出元素工具栏
            	showToolsWindow();
            }
        });
		
		//开始录像
		btn_teaching_video.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            	//资源编码
            	final String fileTime = sdf.format(new Date());
            	final String resourceNo = "resource_"+fileTime;
            	final String imgFileNo = "img_"+fileTime+".png";
            	
            	//=======================截屏上传开始===================================
            	Bitmap ballBitmap =ImageUtil.drawBitmapFromDesk(billiards_desk_view.getWidth(),billiards_desk_view.getHeight(),imgFileNo);
            	
            	File ballFile =null;
				try {
					ballFile = ImageUtil.saveBitmap(ballBitmap, imgFileNo);
				} catch (IOException e) {
					e.printStackTrace();
				}
            	
            	//实例化HttpUtils对象， 参数设置链接超时
            	HttpUtils HTTP_UTILS = new HttpUtils(60 * 1000);
            	//实例化RequestParams对象
            	RequestParams requestParams = new RequestParams();
            	//requestParams.setContentType("multipart/form-data");
            	requestParams.addBodyParameter("fileno", imgFileNo);
            	requestParams.addBodyParameter("no", resourceNo);
            	requestParams.addBodyParameter("file", ballFile, "image/png");
            	String uploadUrl = getResources().getString(R.string.api_image_upload);
            	//通过HTTP_UTILS来发送post请求， 并书写回调函数
            	HTTP_UTILS.send(HttpMethod.POST, uploadUrl, requestParams, new RequestCallBack<String>() {
	            	 @Override
	            	 public void onFailure(HttpException httpException, String arg1) {
	            		 L.d("====截屏上传失败开始=====");
	            		 L.d(httpException.getMessage());
	            		 httpException.printStackTrace();
	            		 L.d("====截屏上传失败结束=====");
	            	 }
	
	            	 @Override
	            	 public void onSuccess(ResponseInfo<String> responseInfo) {
	            		L.d("====截屏上传成功======");
	            		if(!Constant.IS_DEBUG)
	                 	{
	                 		new Runnable() {
	         					@Override
	         					public void run() {
	         						String sendSocketMsg = "{\"method\":\""+Constant.SOCKET_METHOD_BEGIN_VEDIO+"\",\"videono\":\""+resourceNo+"\"}";
	         						L.d("sendSocketMsg=="+sendSocketMsg);
	         						socketClient.send(sendSocketMsg);
	         					}
	         				}.run();
	                 	}
	            		
	            		String uploadResult = responseInfo.result;
	            		SocketData sd = new Gson().fromJson(uploadResult,SocketData.class);
	            		int imgFileId = sd.getFileId();
	            		
	            		L.d("uploadResult==="+uploadResult);
	            		L.d("imgFileId==="+imgFileId);
	            		
	            		//进入录像界面
	            		gotoVedio(imgFileId,imgFileNo,resourceNo);
	            	 }
            	 });
            }
        });
	}
	
	/**
	 * 去录像
	 * @param imgFileId
	 * @param imgFileNo
	 * @param resourceNo
	 */
	private void gotoVedio(int imgFileId,String imgFileNo,String resourceNo)
	{
		//进入录像activity
		Intent intent = new Intent(TeachingMainActivity.this,VedioActivity.class);
		intent.putExtra("imgFileId",imgFileId);
		intent.putExtra("fileno",imgFileNo);
		intent.putExtra("no",resourceNo);
		intent.putExtra("resourceSmallType",flag_teaching_select_ype);
		
		StringBuilder qiuxingData = new StringBuilder();
		qiuxingData.append(ballsPositionData);
		//qd,YS,TAR,K,TYPE
		//拼装进球袋
		qiuxingData.append("|qd:"+Desk.selectedBag);
		
		//拼装元素
		Element ele = null;
		float x=0f;
		float y=0f;
		//float radius=0f;
		for (int i = 0; i < Desk.elementList.size(); i++) {
			ele =  Desk.elementList.get(i);
			x = (ele.getX()-Constant.OFFSET_X)/((Constant.imgDeskW-2*Constant.imgDeskFrame)*Constant.ratio);
			y = (ele.getY()-Constant.OFFSET_Y)/((Constant.imgDeskH-2*Constant.imgDeskFrame)*Constant.ratio);
			//radius = ele.getRadius()/((Constant.imgDeskW-2*Constant.imgDeskFrame)*Constant.ratio);
			qiuxingData.append("|YS").append(ele.getElementType()).append(":").append(x).append(",");
			qiuxingData.append(y).append(",").append(ele.getRadius()).append(",").append(ele.getId());
		}
		//
		
		//拼装目标球
		if(null != Desk.selectedBall)
		{
			qiuxingData.append("|TAR:"+Desk.selectedBall.getNo());
		}
		
		//拼装K球
		if(null != Desk.selectedKBall)
		{
			qiuxingData.append("|K:"+Desk.selectedKBall.getNo());
		}
		
		//拼装类型 
		qiuxingData.append("|TYPE:"+Constant.resourceSmallTypeTransform(flag_teaching_select_ype));
		
		intent.putExtra("ballsPositionData",qiuxingData.toString());
		startActivity(intent);
		Desk.clear();
		if(null  != toast)
		{
			toast.cancel();
		}
		finish();
	}
	
	/**
	 * 测试用加载球型
	 * TODO
	 */
	private void loadBalls(){
		float ballRadius = Constant.imgBallDiameter/2*Constant.ballRatio;
		for (int i = 1; i <= 22; i+=5) {
			Ball ball = new Ball();
			ball.setNo(i%17);
			ball.setBitmap(getBallBitmapByNo(i%15+1));
			ball.setX(Constant.OFFSET_X+ballRadius);
			ball.setY(Constant.OFFSET_Y+ballRadius*(i*2-1));
			
			ball.setCanIn(true);
			ball.setCanInBag(new int[]{0,1,2,3,4,5});
			Desk.canInBallList.add(ball);
			
			L.d("ball"+i+"===="+ball.getBitmap());
		}
		//billiards_desk_view.myDraw();
		btn_teaching_collection.setEnabled(false);
	}
	

	/**
	 * 选择教案类型对话框
	 */
	private void selectTeachTypeDialog(Context context){
    	AlertDialog.Builder builder = new AlertDialog.Builder(context);
    	
    	LayoutInflater flater = LayoutInflater.from(TeachingMainActivity.this);
    	final View view = flater.inflate(R.layout.layout_select_teach_type, null);
    	builder.setIcon(android.R.drawable.ic_dialog_info);
    	builder.setTitle("请选择教案类型");
    	builder.setView(view);
    	builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
				if(null == flag_teaching_select_ype)
				{
					showToast("请选择教案类型");
					//用于不关闭对话框
					try {
						Field field = dialog.getClass().getSuperclass()
								.getDeclaredField("mShowing");
						field.setAccessible(true);
						field.set(dialog, false);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}else
				{
					Desk.STEP_FLAG=Desk.STEP_FLAG_SELECTED_TYPE;
					Desk.RESOURCE_TEACHING_TYPE=flag_teaching_select_ype;
					
					//选中K球
					if(Constant.RESOURCE_SMALL_TYPE_KQIU.equals(flag_teaching_select_ype))
	            	{
						showToast("请添加元素后，再选择目标球");
						socketClient.send("{\"method\":\""+Constant.SOCKET_METHOD_TEACHING_KQIU+"\"}");
	            	}
					//选中防守
					if(Constant.RESOURCE_SMALL_TYPE_FANGSHOU.equals(flag_teaching_select_ype))
	            	{
						showToast("请添加元素后，再选择要击打的球");
						socketClient.send("{\"method\":\""+Constant.SOCKET_METHOD_TEACHING_FANGSHOU+"\"}");
	            	}
					//选中解球
					if(Constant.RESOURCE_SMALL_TYPE_JIEQIU.equals(flag_teaching_select_ype))
	            	{
						showToast("请添加元素后，再选择要解的球");
						socketClient.send("{\"method\":\""+Constant.SOCKET_METHOD_TEACHING_JIEQIU+"\"}");
	            	}
					
					//如果设置的为走位，则默认放一个走位元素
	            	if(Constant.RESOURCE_SMALL_TYPE_ZOUWEI.equals(flag_teaching_select_ype))
	            	{
	            		socketClient.send("{\"method\":\""+Constant.SOCKET_METHOD_TEACHING_ZOUWEI+"\"}");
	            		putElement(Constant.ELEMENT_TYPE_ZOUWEI);
	                	showToast("请拖动停球区域和元素到位后，再选择目标球");
	            	}
					btn_teaching_tools.setEnabled(true);
					//btn_teaching_reselect.setEnabled(true);
					billiards_desk_view.myDraw();
				}
			}
		});
    	builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				flag_teaching_select_ype = null;
				Desk.clear();
				billiards_desk_view.myDraw();
				btn_teaching_collection.setEnabled(true);
				
				//通知亚涛清台 
        		socketClient.send("{\"method\":\""+Constant.SOCKET_METHOD_CLEAR+"\"}");
				
				try {
					Field field = dialog.getClass().getSuperclass()
							.getDeclaredField("mShowing");
					field.setAccessible(true);
					field.set(dialog, true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
    	
    	radio_teaching_select_ype = (RadioGroup)view.findViewById(R.id.radio_teaching_select_ype);
		radio_teaching_select_ype.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override 
            public void onCheckedChanged(RadioGroup group, int checkedId) {  
            	L.d("checkedId="+checkedId);
                if(checkedId==R.id.radio_teaching_zouwei){
                	flag_teaching_select_ype = Constant.RESOURCE_SMALL_TYPE_ZOUWEI;
                }
                else if(checkedId==R.id.radio_teaching_kqiu){
                	flag_teaching_select_ype = Constant.RESOURCE_SMALL_TYPE_KQIU;
                }
                else if(checkedId==R.id.radio_teaching_jieqiu){
                	flag_teaching_select_ype = Constant.RESOURCE_SMALL_TYPE_JIEQIU;;
                }  
                else if(checkedId==R.id.radio_teaching_fangshou){
                	flag_teaching_select_ype = Constant.RESOURCE_SMALL_TYPE_FANGSHOU;
                }
                L.d("flag_teaching_select_ype="+flag_teaching_select_ype);
            }  
        });  
    	
		AlertDialog dialog = builder.create();
    	dialog.setCanceledOnTouchOutside(false);
    	dialog.show();
    }
	
	
	/**
	 * 弹出工具栏
	 */
	private void showToolsWindow() {
		View popView = View.inflate(this, R.layout.layout_tools, null);

		//工具(雷区，红包等)
	    ImageView tools_leiqu = (ImageView) popView.findViewById(R.id.tools_leiqu);
	    ImageView tools_hongbao= (ImageView) popView.findViewById(R.id.tools_hongbao);
	    ImageView tools_zouwei= (ImageView) popView.findViewById(R.id.tools_zouwei);
	    ImageView tools_zayaobao= (ImageView) popView.findViewById(R.id.tools_zayaobao);
	    ImageView tools_hedan= (ImageView) popView.findViewById(R.id.tools_hedan);
	    ImageView tools_lijuan= (ImageView) popView.findViewById(R.id.tools_lijuan);
	    
		int width = Constant.screenW*2/3;
		int height = Constant.screenH/6;

		final PopupWindow popWindow = new PopupWindow(popView,width,height);
		popWindow.setFocusable(true);
		popWindow.setOutsideTouchable(true);// 设置允许在外点击消失

		OnClickListener listener = new OnClickListener() {
			public void onClick(View v) {
				L.d("v.getId()==="+v.getId());
				switch (v.getId()) {
				case R.id.tools_leiqu:
                	putElement(Constant.ELEMENT_TYPE_LEIQU);
					break;
				case R.id.tools_hongbao:
					putElement(Constant.ELEMENT_TYPE_HONGBAO);
					break;
				case R.id.tools_lijuan:
					putElement(Constant.ELEMENT_TYPE_LIJUAN);
					break;
					
				case R.id.tools_zouwei:
					putElement(Constant.ELEMENT_TYPE_ZOUWEI);
					break;
					
				case R.id.tools_zayaobao:
					putElement(Constant.ELEMENT_TYPE_ZAYAOBAO);
					break;
					
				case R.id.tools_hedan:
					putElement(Constant.ELEMENT_TYPE_HEDAN);
					break;
				}
				popWindow.dismiss();
			}
		};

		tools_leiqu.setOnClickListener(listener);
		tools_hongbao.setOnClickListener(listener);
		tools_zouwei.setOnClickListener(listener);
		tools_zayaobao.setOnClickListener(listener);
		tools_hedan.setOnClickListener(listener);
		tools_lijuan.setOnClickListener(listener);
		
		ColorDrawable dw = new ColorDrawable(R.color.gray);
		popWindow.setBackgroundDrawable(dw);
		int yoff = -Constant.screenW/3+btn_teaching_tools.getWidth()/2;
		popWindow.showAsDropDown(btn_teaching_tools,yoff,5);
	}
	
	/**
	 * 向球桌添加元素
	 * @param elementType
	 */
	private void putElement(Integer elementType)
	{
		Element element = new Element();
		element.setElementType(elementType);
		//element.setRadius(Constant.imgBallDiameter*Constant.ballRatio*2);
		float radius = 0.05f;
		
		if(Constant.ELEMENT_TYPE_LEIQU.equals(elementType))
		{
			radius = 50.0f/1024/2.0f;
		}else if(Constant.ELEMENT_TYPE_HONGBAO.equals(elementType))
		{
			radius = 100.0f/1024/2.0f;
		}else if(Constant.ELEMENT_TYPE_ZOUWEI.equals(elementType))
		{
			radius = 150.0f/1024/2.0f;
		}else if(Constant.ELEMENT_TYPE_LIJUAN.equals(elementType))
		{
			radius = 133.0f/1024/2.0f;
		}else if(Constant.ELEMENT_TYPE_ZAYAOBAO.equals(elementType))
		{
			radius = 52.0f/1024/2.0f;
		}else if(Constant.ELEMENT_TYPE_HEDAN.equals(elementType))
		{
			radius = 170.0f/1024/2.0f;
		}
		element.setRadius(radius);
		element.setX(Constant.OFFSET_X+(Constant.imgDeskW-2*Constant.imgDeskFrame)*Constant.ratio/2);
		element.setY(Constant.OFFSET_Y+(Constant.imgDeskH-2*Constant.imgDeskFrame)*Constant.ratio/2);
		element.setId(Desk.elementList.size());
		Desk.elementList.add(element);
		
		Desk.ELEMENT_CURRENT_INDEX=Desk.elementList.size()-1;
		billiards_desk_view.setAndSendElementPosition((int)element.getX(), (int)element.getY(), false);
    	billiards_desk_view.myDraw();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	public void onDestory(){
		L.d("TeachingMainActivity===="+this);
	    super.onDestroy();
	} 
	
	/**
	 * 显示Toast,防止延迟
	 * @param msg
	 */
	private void showToast(String msg){
		if (toast != null)
	    {
	        toast.setText(msg);
	        toast.setDuration(Toast.LENGTH_LONG);
	        toast.show();
	    } else
	    {
	        toast = Toast.makeText(TeachingMainActivity.this, msg, Toast.LENGTH_LONG);
	        toast.show();
	    }
	}
	
	//===========================禁用home键，返回键和菜单键====================================
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return false;
		} else if (keyCode == KeyEvent.KEYCODE_MENU) {
			return false;
		} else if (keyCode == KeyEvent.KEYCODE_HOME) {
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
}